﻿using FastBuild.Init.TimeJob;
using FastBuild.TimeJob;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Reflection;

namespace FastBuild
{
    /// <summary>
    /// 
    /// </summary>
    public static class IISRestartInitExtension
    {
        /// <summary>
        /// 启用TimeJob
        /// </summary>
        /// <param name="option"></param>
        /// <param name="action"></param>
        public static InitOption UseTimeJob(this InitOption option, Action<TimeJobInitOption> action)
        {
            TimeJobInitOption moduleOption = new TimeJobInitOption();
            action?.Invoke(moduleOption);
            if (option != null)
                InitClass.Option = moduleOption;

            return option;
        }

        /// <summary>
        /// 启用TimeJob
        /// </summary>
        public static InitOption UseTimeJob(this InitOption option)
        {
            InitClass.Option = new TimeJobInitOption();

            return option;
        }
    }
}

namespace FastBuild.Init.TimeJob
{
    /// <summary>
    /// 
    /// </summary>
    public static class InitClass
    {
        /// <summary>
        /// Option
        /// </summary>
        public static TimeJobInitOption Option { get; set; }

        /// <summary>
        /// 初始化TimeJob定时任务
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection InitMethod_ServiceCollection(this IServiceCollection services)
        {
            #region 注入Job
            Assembly assemblies = Assembly.GetEntryAssembly();

            List<TypeInfo> list = assemblies.DefinedTypes.Where(y => y.GetInterface(nameof(IJob)) is not null).ToList();
            foreach (var item in list)
            {
                services.AddScoped(item);
            }
            #endregion

            return services;
        }

        /// <summary>
        /// 初始化TimeJob定时任务
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        public static WebApplication InitMethod_WebApplication(this WebApplication app)
        {
            (ServiceProviderExtension.GetServiceWithAutowired<ITimeJobService>(app.Services) as TimeJobService)?.Run();

            return app.ConsoleWriteLine($"TimeJob Init Success");
        }
    }
}
